// pages/bargain/bargain.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    hasLogin: false,
    currentValue: 50,
    kanList: [],
    isDoing: false, // 我是否有正在进行中的砍价
    ishelped: false, //当前页面订单是否已经帮砍过
    other_bargainingId: '', //点击分享时候的  别人的砍价单号
    my_bargainingId: '', //点击分享时候的  自己的砍价单号
    bargainingId: '', //当前页面的订单bargainingId

    userId: wx.getStorageSync('userId'), //自己的userid
    other_userId: null, //跳转来的别人的userid
    bargainingInfo: null, //砍价全部信息
    surplus: 9.9, //剩余
    success: 0, //本条订单已砍金额
    money: 0, //总金额
    successPercent: 0, //进度条按照100计算  要*10
  },

  onDrag(event) {
    this.setData({
      currentValue: event.detail.value,
    });
  },
  getList() {
    var kanList = [{
      phone: "18120163279",
      tip: "已砍0.30元"
    }]
    var changeStr = '****'
    kanList.forEach((items, i) => {
      items.phone = items.phone.substr(0, 3) + changeStr + items.phone.substr(7, changeStr.length);
    })
    this.setData({
      kanList: this.group(kanList, 4)
    })
  },

  /**
  * 我是否有正在进行中的砍价
  * @param {
   * 请求URL
   ` 127.0.0.1:5006/manage/client/bargaining/bargain
    GET
   } 
   } 
   */
  getBargaining() {
    var getObj = {
      url: '/manage/client/bargaining/bargain',
      method: 'POST',
      data: {
        userId: wx.getStorageSync('userId'),
        token: wx.getStorageSync('token')
      }
    }
    app.request.gameRequest(getObj).then(res => {
      console.log('我是否有正在进行中的砍价', res)
      if (!!res.data.data) {
        this.setData({
          //  有
          isDoing: true, //有正在进行中的订单
          bargainingInfo: res.data.data, //当前订单信息
          bargainingId: res.data.data.bargainingId, //当前页面的订单bargainingId
          my_bargainingId: res.data.data.bargainingId, //点击分享时候的  自己的砍价单号
          success: (res.data.data.money - res.data.data.surplus).toFixed(2), //砍价成功了几块钱
          successPercent: ((res.data.data.money - res.data.data.surplus) * 10 ).toFixed(2) , //处理金额
          surplus: res.data.data.surplus, //还剩
          money: res.data.data.money, //总价
        })
        this.getBargainMeList(res.data.data.bargainingId) //获取给我砍价的人的列表
      } else {
        this.setData({
          // 没有
          isDoing: false
        })
      }


      var other_bargainingId = this.data.other_bargainingId //跳转来的
      var other_userId = this.data.other_userId //跳转来的
      var userId = this.data.userId //自己的userId

      console.log('当前订单号的userid', other_userId)
      console.log('当前订单号', other_bargainingId)
      console.log('我的userid', userId)
    }).catch(err => {
      // console.log('获取个人数据', err)
    })
  },


  /**
   * 发起砍价请求
   * @param {
   * 请求URL
   ` 127.0.0.1:5006/manage/client/bargaining
    POST
    返回示例
    {
        "code": 0,
        "desc": "操作成功"，
        "data": "bargainingId"
    }
    返回参数说明
    参数名	类型	说明
    data	long	砍价主键id
   } 
   } 
   */
  getOneBargain() {
    var getObj = {
      url: '/manage/client/bargaining',
      method: 'POST',
      data: {
        userId: wx.getStorageSync('userId'),
        token: wx.getStorageSync('token')
      }
    }
    app.request.gameRequest(getObj).then(res => {
      console.log('发起砍价请求', res)
      app.success("发起成功!")
      var bargainingId = this.data.data
      this.setData({
        my_bargainingId: bargainingId,
        bargainingId: bargainingId
      })
      // this.getOneBargainInfo(this.data.bargainingId) //获取详细信息
      // this.getIfKanOrder(bargainingId) //我是否已经砍过这条订单
      this.getBargaining() //我是否有正在进行中的砍价
    }).catch(err => {
      // console.log('获取个人数据', err)
    })
  },
  /**
   * 用户点击砍价
   * @param {
    * 请求URL
    `` 127.0.0.1:5006/manage/client/bargaining/reduce
     POST
     参数
     bargainingId	是	long	砍价活动主键
     返回示例
     {
         "code": 0,
         "desc": "操作成功"，
         "data": "bargainingId"
     }
          回参数说明
      参数名	类型	说明
      name	string	区服名称
      districtId	string	主键
    } 
    } 
    */
  //  用户自行砍价
  doMyself() {
    var getObj = {
      url: '/manage/client/bargaining/reduce',
      method: 'POST',
      data: {
        bargainingId: this.data.bargainingId,
        token: wx.getStorageSync('token'),
        userId: wx.getStorageSync('userId'),
      }
    }
    app.request.gameRequest(getObj).then(res => {
      console.log('用户自行砍价', res)
      // app.success("成功助力" + res.data.dat.toFixed(2) * 10 + '%')
      // app.success("成功助力" + (res.data.data* 10).toFixed(2) + '%')
      app.success(`成功助力${(res.data.data*10).toFixed(2)}%`)
      setTimeout(() => {
        this.getIfKanOrder(this.data.bargainingId) //我是否已经砍过这条订单
      }, 1000)
    }).catch(err => {})
  },



  //我要砍这个
  iWantThis() {
    if (!!this.data.userId) { //如果已经登陆
      wx.redirectTo({
        url: '/pages/bargain/bargain',
      })
    } else { //如果没有登陆
      wx.navigateTo({
        url: '/pages/index/index',
      })
    }
  },


  /**
   * 获取我发布的砍价详情
   * @param {
   * 请求URL
   127.0.0.1:5006/manage/client/bargaining/{bargainingId}
   GET
   } 
   */
  getOneBargainInfo(bargainingId) {
    var getObj = {
      url: `/manage/client/bargaining/${bargainingId}`,
      method: 'GET'
    }

    app.request.gameRequest(getObj).then(res => {
      console.log('获取我发布的砍价详情', res)
      this.setData({
        bargainingInfo: res.data.data, //当前订单信息
        success: (res.data.data.money - res.data.data.surplus).toFixed(2), //砍价成功了几块钱
        successPercent: ((res.data.data.money - res.data.data.surplus) * 10 ).toFixed(2) , //处理金额
        surplus: res.data.data.surplus, //还剩
        money: res.data.data.money, //总价
      })
    }).catch(err => {
      // console.log('获取个人数据', err)
    })
  },



  /**
   * 获取给我砍价的人的列表
   * @param {
    * 请求URL
    127.0.0.1:5006/manage/client/bargain/list
    GET
    参数
参数名	必选	类型	说明
bargainingId	是	long	砍价活动主键
    } 
    } 
    */

  getBargainMeList() {
    var getObj = {
      url: '/manage/client/bargain/list',
      method: 'GET',
      data: {
        bargainingId: this.data.bargainingId,
        // token: wx.getStorageSync('token'),
        // userId: wx.getStorageSync('userId'),
      }
    }
    app.request.gameRequest(getObj).then(res => {
      console.log('获取我给我砍价的人的列表', res)
      var list = res.data.data
      var kanList = []

      list.forEach((items, i) => {
        // var obj = {
        //   phone: items.ywpdDynamic.telephone,
        //   tip: `已砍${items.money}元`
        // }
        // var obj = {
        //   phone: items.ywpdDynamic.telephone,
        //   tip: `已助力${ Number(items.money ) .toFixed(2) * 10}%`
        // }
        var obj = {
          phone: items.ywpdDynamic.telephone,
          tip: `已助力${ (items.money* 10).toFixed(2) }%`
        }


        kanList.push(obj)
      })
      var changeStr = '****'
      kanList.forEach((items, i) => {
        items.phone = items.phone.substr(0, 3) + changeStr + items.phone.substr(7, changeStr.length);
      })
      this.setData({
        kanList: this.group(kanList, 4)
      })
    }).catch(err => {
      // console.log('获取个人数据', err)
    })
  },
  // 
  /**
   * 我是否已经砍过这条订单
   * @param {
    * 请求URL
    /client/bargain/skip
    GET
    } 
    } 
    */
  getIfKanOrder(bargainingId) {
    var getObj = {
      url: `/manage/client/bargain/skip`,
      method: 'POST',
      data: {
        bargainingId: bargainingId,
        userId: this.data.userId
      },
    }
    app.request.gameRequest(getObj).then(res => {
      console.log('我是否已经砍过这条订单', res)
      var data = res.data.data
      if (!!data) {
        //已经帮砍过当前页面订单
        this.setData({
          ishelped: true
        })

      } else {
        //没有帮砍过当前页面订单
        this.setData({
          ishelped: false
        })
      }
      this.getBargainMeList() //获取给我砍价的人的列表
      this.getOneBargainInfo(bargainingId) //获取详细信息
    }).catch(err => {
      // console.log('获取个人数据', err)
    })
  },






  // 将数组array分成长度为subGroupLength的小数组并返回新数组
  group(array, subGroupLength) {
    let index = 0;
    let newArray = [];
    while (index < array.length) {
      newArray.push(array.slice(index, index += subGroupLength));
    }
    return newArray;
  },


  // 支付授权
  wxLogin() {
    let that = this

    console.log('app.globalData.hasLogin',app.globalData.hasLogin)
    if (this.data.hasLogin == false) {
      wx.navigateTo({
        url: '/pages/wxLogin/wxLogin',
      })
    } else {
      wx.login({
        success: function (res) {
          console.log('用户参数', res);
          var code = res.code
          var getObj = {
            url: `/manage/client/bargaining/pay`,
            method: 'POST',
            data: {
              bargainingId: that.data.bargainingId,
              code: code,
              token: wx.getStorageSync('token'),
              userId: wx.getStorageSync('userId'),
            },
          }
          app.request.gameRequest(getObj).then(res => {
            // console.log('支付信息', res)
            let prepay = res.data.data
            wx.requestPayment({
              "timeStamp": prepay.timeStamp,
              "nonceStr": prepay.nonceStr,
              "package": prepay.packageValue,
              "signType": prepay.signType,
              "paySign": prepay.paySign,
              "success": res => {
                app.success("助力成功！")
                setTimeout(() => {
                  // wx.navigateBack({
                  //   delta: 1,
                  // })
                  wx.switchTab({
                    url: '/pages/my/my',
                  })
                }, 1000)
                console.log("订单确定", res);
              },
              "fail": res => {
                console.log("订单取消", res);
                app.error("支付拼团失败！")
              }
            });
          }).catch(err => {
            // console.log('获取个人数据', err)
          })
        },
        fail: function (err) {}
      });
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    this.getBargaining() //我是否有正在进行中的砍价



  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    setTimeout(() => {
      // 自己主动来的  首先判断登陆
      app.util.checkLogin().then(() => {

        this.setData({
          hasLogin: app.globalData.hasLogin
        })
        
      }).catch(() => {
        wx.navigateTo({
          url: '/pages/index/index',
        })
      })
    }, 500)

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var bargainingId = this.data.bargainingId

    return {
      title: '助力免费拿',
      desc: '一起助力免费拿',
      path: '/pages/bargain/shareBargain?bargainingId=' + bargainingId + '&userId=' + wx.getStorageSync('userId') // 路径，传递参数到指定页面。
    }

  }
})